package com.leetcode.search.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/7/26 22:33
 */
public class LetterCombinations_17 {

    // 电话表
    private static final String[] KEYS =
            {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    String digits;

    List<String> res = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if(digits.equals("")) return res;
        this.digits = digits;
        backtrack(0, new StringBuilder());
        return res;
    }

    private void backtrack(int start, StringBuilder sb) {
        if (sb.length() == digits.length()) {
            // 满足回溯条件
            res.add(sb.toString());
            return;
        }
        // 获取当前digit位置的String key
        String key = KEYS[digits.charAt(start) - '0'];
        // 遍历当前按键可能存在多少字符
        for (int i = 0; i < key.length(); i++) {
            // 决策
            sb.append(key.charAt(i));
            // 递归决策
            backtrack(start + 1, sb);
            // 回溯
            sb.deleteCharAt(sb.length() - 1);
        }
    }

}
